from flask import Blueprint, request, g
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render, iPagenation
from common.models.work_list import WorkList
from common.models.user import User
from common.models.document import Document
from application import db
from common.libs.DataHelper import getCurrentTime
import datetime
from dateutil.relativedelta import *

work_page = Blueprint("work_page", __name__)


# 通用函数区

@work_page.route("/index", methods=["GET", "POST"])
def work_index():
    starttime = request.args.get('starttime')
    endtime = request.args.get('endtime')
    pickup = request.args.get('pickup')
    show = request.args.get('show')
    diedata = datetime.datetime.now().strftime("%Y-%m-%d")
    warndata = datetime.datetime.now() + relativedelta(days=+1)
    warndata = warndata.strftime("%Y-%m-%d")

    if pickup == "yes":
        uid = g.current_user.id
        listdatadoing = WorkList.query.filter_by(uid=uid, listtask="计划", ).all()
        listdatadone = WorkList.query.filter_by(uid=uid, listtask="完成", ).filter(
            WorkList.listdata.between(starttime, endtime)).order_by(WorkList.listdata.desc())
        req = request.values
        page = 1
        if 'p' in req and req['p']:
            page = int(req['p'])
        url = '/work/index?starttime=' + starttime + "&endtime=" + endtime + "&pickup=yes"
        page_params = {
            'total_count': listdatadone.count(),
            "page_size": 3,
            'page': page,
            'url': url
        }
        pages = iPagenation(page_params)
        # -1 - 30,30 - 60 ,60 - 90
        offset = (page - 1) * page_params['page_size']
        limit = page * page_params['page_size']
        listdatadone = listdatadone[offset:limit]
        return ops_render("workspace/work_layout.html",
                          {"listdatadoing": listdatadoing, "listdatadone": listdatadone, "pages": pages,
                           "diedata": diedata, "warndata": warndata, "show": show})

    else:
        enddate = datetime.datetime.now().strftime("%Y-%m-%d")
        stadate = datetime.datetime.now() + relativedelta(months=-2)
        stadate = stadate.strftime("%Y-%m-%d")

        uid = g.current_user.id
        listdatadoing = WorkList.query.filter_by(uid=uid, listtask="计划", ).order_by(WorkList.listdata).all()
        listdatadone = WorkList.query.filter_by(uid=uid, listtask="完成", ).filter(
            WorkList.listdata.between(stadate, enddate)).order_by(WorkList.listdata.desc())
        mycreatelist = WorkList.query.filter(WorkList.createuid == uid, WorkList.uid != uid,
                                             WorkList.listtask == "计划", ).order_by(WorkList.listdata).all()
        # 分页
        req = request.values
        page = 1
        if 'p' in req and req['p']:
            page = int(req['p'])

        page_params = {
            'total_count': listdatadone.count(),
            "page_size": 3,
            'page': page,
            'url': "/work/index?"
        }
        pages = iPagenation(page_params)
        # -1 - 30,30 - 60 ,60 - 90
        offset = (page - 1) * page_params['page_size']
        limit = page * page_params['page_size']
        listdatadone = listdatadone[offset:limit]
        return ops_render("workspace/work_layout.html",
                          {"listdatadoing": listdatadoing, "listdatadone": listdatadone, "pages": pages,
                           "diedata": diedata, "warndata": warndata, "show": show, "mycreatelist": mycreatelist})


@work_page.route("/lookupuser", methods=["GET", "POST"])
def lookupuser():
    req = request.values
    name = req['name'] if "name" in req else ""
    userinfo = User.query.filter_by(nickname=name).first()
    if userinfo is None:
        return ops_renderJSON(msg="没这人~~！")
    else:
        return ops_renderJSON(msg="用户信息有效",
                              data={"id": userinfo.id, "name": userinfo.nickname, "dep": userinfo.department,
                                    "company": userinfo.company})


@work_page.route("/changeuser", methods=["GET", "POST"])
def changeuser():
    req = request.values
    uid = req['uid'] if "uid" in req else ""
    taskid = req['id'] if "id" in req else ""
    listinfo = WorkList.query.filter_by(id=taskid).first()
    listinfo.uid = uid
    db.session.commit()
    return ops_renderJSON(msg="任务委派成功")


@work_page.route("/changetask", methods=["GET", "POST"])
def changetask():
    req = request.values
    listdata = req['listdata'] if "listdata" in req else ""
    listcontent = req['listcontent'] if "listcontent" in req else ""
    listtask = req['listtask'] if "listtask" in req else ""
    listremark = req['listremark'] if "listremark" in req else ""
    weight = req['weight'] if "weight" in req else ""
    classone = req['classone'] if "classone" in req else ""
    classtwo = req['classtwo'] if "classtwo" in req else ""
    classthree = req['classthree'] if "classthree" in req else ""
    classfour = req['classfour'] if "classfour" in req else ""
    classfive = req['classfive'] if "classfive" in req else ""
    method = req['method'] if "method" in req else ""
    updataid = req['updataid'] if "updataid" in req else ""
    if method == "updata":
        updata = WorkList.query.filter_by(id=updataid).first()
        updata.listdata = listdata
        updata.listcontent = listcontent
        updata.listremark = listremark
        updata.weight = weight
        updata.classone = classone
        updata.classtwo = classtwo
        updata.classthree = classthree
        updata.classfour = classfour
        updata.classfive = classfive
        updata.uid = g.current_user.id
        updata.updated_time = getCurrentTime()
        db.session.commit()
        return ops_renderJSON(msg="任务卡修改成功")
    if method == "getback":
        getback = WorkList.query.filter_by(id=updataid).first()
        getback.uid = g.current_user.id
        getback.updated_time = getCurrentTime()
        db.session.commit()
        return ops_renderJSON(msg="任务卡取回成功")
    else:
        task = WorkList.query.filter_by(id=updataid).first()
        task.listtask = listtask
        task.updated_time = getCurrentTime()
        db.session.commit()
        return ops_renderJSON(msg="任务卡操作成功")


# 模版区
@work_page.route("/itfix", methods=["GET", "POST"])
def work_itfix():
    if request.method == "GET":
        id = request.args.get("id")
        stat = request.args.get("stat")
        # type=request.args.get("document")
        document = Document.query.filter_by(type="IT类",classone="管理制度").first()
        content=document.content
        if stat is None:
            if id is None:
                taskinfo = {}
                flag = 0
                return ops_render("workspace/workcardtemp/it_fix.html", {"taskinfo": taskinfo, "flag": flag,"content": content})
            else:
                taskinfo = WorkList.query.filter_by(id=id).first()
                flag = 3
                return ops_render("workspace/workcardtemp/it_fix.html", {"taskinfo": taskinfo, "flag": flag,"content": content})
        if stat == "2":
            taskinfo = {}
            flag = 2
            return ops_render("workspace/workcardtemp/it_fix.html",
                              {"taskinfo": taskinfo, "flag": flag,"content": content})
        else:
            taskinfo = WorkList.query.filter_by(id=id, ).first()
            flag = 1
            return ops_render("workspace/workcardtemp/it_fix.html", {"taskinfo": taskinfo, "flag": flag,"content": content})
    if request.method == "POST":
        req = request.values
        listdata = req['listdata'] if "listdata" in req else ""
        listcontent = req['listcontent'] if "listcontent" in req else ""
        listtask = req['listtask'] if "listtask" in req else ""
        listremark = req['listremark'] if "listremark" in req else ""
        type = req['type'] if "type" in req else ""
        weight = req['weight'] if "weight" in req else ""
        classone = req['classone'] if "classone" in req else ""
        classtwo = req['classtwo'] if "classtwo" in req else ""

        worklist = WorkList()
        worklist.listdata = listdata
        worklist.listcontent = listcontent
        worklist.listremark = listremark
        worklist.listtask = listtask
        worklist.type = type
        worklist.weight = weight
        worklist.classone = classone
        worklist.classtwo = classtwo
        worklist.uid = worklist.createuid = g.current_user.id
        worklist.created_time = worklist.updated_time = getCurrentTime()
        db.session.add(worklist)
        db.session.commit()
        return ops_renderJSON(msg="任务卡新建成功")

@work_page.route("/itprogram", methods=["GET", "POST"])
def work_itprogram():
    if request.method == "GET":
        id = request.args.get("id")
        stat = request.args.get("stat")
        if stat is None:
            if id is None:
                taskinfo = {}
                flag = 0
                return ops_render("workspace/workcardtemp/it_program.html", {"taskinfo": taskinfo, "flag": flag})
            else:
                taskinfo = WorkList.query.filter_by(id=id).first()
                flag = 3
                return ops_render("workspace/workcardtemp/it_program.html", {"taskinfo": taskinfo, "flag": flag})
        if stat == "2":
            taskinfo = {}
            flag = 2
            return ops_render("workspace/workcardtemp/it_program.html",
                              {"taskinfo": taskinfo, "flag": flag})
        else:
            taskinfo = WorkList.query.filter_by(id=id, ).first()
            flag = 1
            return ops_render("workspace/workcardtemp/it_program.html", {"taskinfo": taskinfo, "flag": flag})
    if request.method == "POST":
        req = request.values
        listdata = req['listdata'] if "listdata" in req else ""
        listcontent = req['listcontent'] if "listcontent" in req else ""
        listtask = req['listtask'] if "listtask" in req else ""
        listremark = req['listremark'] if "listremark" in req else ""
        type = req['type'] if "type" in req else ""
        weight = req['weight'] if "weight" in req else ""
        classone = req['classone'] if "classone" in req else ""
        classtwo = req['classtwo'] if "classtwo" in req else ""
        classthree = req['classthree'] if "classthree" in req else ""

        worklist = WorkList()
        worklist.listdata = listdata
        worklist.listcontent = listcontent
        worklist.listremark = listremark
        worklist.listtask = listtask
        worklist.type = type
        worklist.weight = weight
        worklist.classone = classone
        worklist.classtwo = classtwo
        worklist.classthree = classthree
        worklist.uid = worklist.createuid = g.current_user.id
        worklist.created_time = worklist.updated_time = getCurrentTime()
        db.session.add(worklist)
        db.session.commit()
        return ops_renderJSON(msg="任务卡新建成功")